import {FormControl, FormGroup, Validators} from '@angular/forms';
import {AbstractControl} from '@angular/forms/src/model';
import {ValidationErrors} from '@angular/forms/src/directives/validators';

// 手机号校验函数(以1开头的11位纯数字)
export const mobileValidator = (control: FormControl): any => {
  if (control && control.value !== null) {
    const myReg = /^1\d{10}$/;
    const valid = myReg.test(control.value);
    return valid ? null : {mobile: '手机号码不正确'};
  }
  return null;
};

// 验证码校验函数(6位纯数字)
export const qrcodeValidator = (control: FormControl): any => {
  if (control && control.value !== null) {
    const myReg = /^\d{6}$/;
    const valid = myReg.test(control.value);
    return valid ? null : {qrcode: '验证码错误'};
  }
  return null;
};

// 验证身份证号码合法性(15位或18位)
export const idNumberValidator = (control: FormControl): any => {
  if (control && control.value) {
    const myReg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
    const valid = myReg.test(control.value);
    return valid ? null : {idNumber: '身份证号码不正确'};
  }
  return null;
};

// 验证值是否为有效(不可为0，false，null，undefined，空字符串)
export const requiredZero = (control: AbstractControl): ValidationErrors | null => {
  if (control && !control.value) {
    return {zero: '请选择一个选项'};
  }
  return null;
};

// 验证值是否为1000的整数倍
export const thousandTimesValidator = (control: AbstractControl): ValidationErrors | null => {
  if (control && control.value !== null) {
    const errObj = {thousandTimes: '请输入1000的整数倍'};
    if (typeof control.value !== 'number' || control.value < 1000) {
      return errObj;
    } else {
      const valid = control.value % 1000;
      return valid === 0 ? null : {thousandTimes: '请输入1000的整数倍'};
    }
  }
  return null;
};

// 邮箱校验函数
export function emailValidator(control: FormControl): any {
  if (control && control.value.trim()) {
    return Validators.email(control);
  }
  return null;
}

// 密码一致性校验
export function equalValidator(group: FormGroup): any {
  // 使用get方法得到的是AbstractControl类型，需要向下转型
  const newPassword: FormControl = group.get('newPassword') as FormControl;
  const conNewPassword: FormControl = group.get('conNewPassword') as FormControl;
  if (newPassword !== null && conNewPassword !== null) {
    const valid: boolean = (newPassword.value === conNewPassword.value);
    // console.log('equalValidator:' + valid);
    return valid ? null : {equal: '密码确认不一致'};
  }
  return null;
}
